const path = require('path');
const webpack = require('webpack');
const glob = require('glob');

const CleanWebpackPlugin = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require("extract-text-webpack-plugin");

const jquery = require("jquery");

var entry = getEntry('src/js/**/*.js');

var config = {
    entry: entry,
    plugins: [
        new CleanWebpackPlugin(['dist']),
        new ExtractTextPlugin({
            filename:"css/[name].css",
            allChunks:true
        }),
        new webpack.ProvidePlugin({
            $: jquery,
            jQuery:jquery,
            "window.jQuery":jquery
        })

    ],
    output: {
        path: path.join(__dirname, 'dist'), //输出目录的配置，模板、样式、脚本、图片等资源的路径配置都相对于它
        filename: 'js/[name].js',           //每个页面对应的主js的生成配置
        //chunkFilename: 'js/[id].chunk.js'   //chunk生成的配置
    },
    module: {
        rules: [ //加载器，关于各个加载器的参数配置，可自行搜索之。
            {
                test: /\.css$/,
                //配置css的抽取器、加载器。'-loader'可以省去
                use: ExtractTextPlugin.extract({
                    fallback: "style-loader",
                    use: "css-loader"
                })
            }, {
                //html模板加载器，可以处理引用的静态资源，默认配置参数attrs=img:src，处理图片的src引用的资源
                //比如你配置，attrs=img:src img:data-src就可以一并处理data-src引用的资源了，就像下面这样
                test: /\.html$/,
                use: "html-loader?attrs=img:src img:data-src"
            }, {
                //文件加载器，处理文件静态资源
                test: /\.(woff|woff2|ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
                use: 'file-loader?name=fonts/[name].[ext]'
            }, {
                //视频加载
                test: /\.(mp4|flv|swf)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
                use: 'file-loader?name=video/[name].[ext]'
            }, {
                //图片加载器，雷同file-loader，更适合图片，可以将较小的图片转成base64，减少http请求
                //如下配置，将小于50000byte的图片转成base64码
                test: /\.(png|jpg|gif)$/,
                use: 'url-loader?limit=5000&name=img/[hash].[ext]'
            }
        ]
    },

    optimization: {

        splitChunks: {
            cacheGroups: {
                commons: {
                    test: /[\\/]node_modules[\\/]/,
                    name: 'common',
                    chunks: 'all'
                }
            },
            filename: "common.[chunkhash].js"
        },

        runtimeChunk: {
            name: "manifest"
        }

    }
};

var viesObj = getView('src/view/**/*.html', 'src/view/')
var pages = Object.keys(viesObj);
pages.forEach(function (pathname) {
    var htmlName = viesObj[pathname]
    var conf = {
        filename: './view/' + htmlName + '.html', //生成的html存放路径，相对于path
        template: './src/view/' + htmlName + '.html', //html模板路径
        inject: 'body', //js插入的位置，true/'head'/'body'/false
        hash: true, //为静态资源生成hash值
        //favicon: './src/img/favicon.ico', //favicon路径，通过webpack引入同时可以生成hash值
        chunks: ["common",htmlName],//需要引入的chunk，不配置就会引入所有页面的资源
        /*
        minify: { //压缩HTML文件
            removeComments: true, //移除HTML中的注释
            collapseWhitespace: false //删除空白符与换行符
        }*/
    };
    config.plugins.push(new HtmlWebpackPlugin(conf));
});

module.exports = config;

function getView(globPath, pathDir) {
    var files = glob.sync(globPath);
    var entries = {},
        entry, dirname, basename, pathname, extname;

    for (var i = 0; i < files.length; i++) {
        entry = files[i];
        dirname = path.dirname(entry);

        extname = path.extname(entry);
        basename = path.basename(entry, extname);
        pathname = path.join(dirname, basename);
        pathname = pathDir ? pathname.replace(new RegExp('^' + pathDir), '') : pathname;
        entries[pathname] = basename;
    }
    return entries;
}

function getEntry(globPath) {
    var files = glob.sync(globPath);
    var entries = {},
        entry, dirname, basename, pathname, extname;

    for (var i = 0; i < files.length; i++) {
        entry = files[i];
        dirname = path.dirname(entry);
        extname = path.extname(entry);
        basename = path.basename(entry, extname);
        pathname = path.join(dirname, basename);
        entries[basename] = './' + entry;
    }
    return entries;
}

